<?php

namespace App\Http\Middleware;

use App\Helpers\Jwt;
use App\Services\MenuService;
use Closure;
use Illuminate\Http\Request;

class CheckAuth
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 验证访问权限
        $action = app('request')->route()->getAction();
        $controller = class_basename($action['controller']);
        list($controller, $action) = explode('@', $controller);

        // 排除无需验证的控制器
        $noLoginActs = ['LoginController', 'IndexController'];
        if (!in_array($controller, $noLoginActs)) {
            // 控制器名
            $controller = strtolower(str_replace("Controller", null, $controller));
            $permission = "sys:{$controller}:{$action}";

            // 获取用户ID
            $token = $request->headers->get('Authorization');
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new Jwt();
            $userId = $jwt->verifyToken($token);
            if ($userId != 1) {
                // 权限节点列表
                $menuService = new MenuService();
                $permissionList = $menuService->getPermissionsList($userId);
                if (!in_array($permission, $permissionList)) {
                    return response()->json(message("暂无权限", false, null, 403));
                }
            }
        }
        return $next($request);
    }
}
